#!/usr/bin/python2.7
# &modem (aka "andmodem")

import sys
import time
import serial

TESTING = 0 # 0='production', 0.5=echo xfer to stdout, 1==dummy client
BLOCKSIZE = 240

startaddr = int(sys.argv[1])
f = open(sys.argv[2], "rb")

if startaddr < 1:
        lo = ord(f.read(1))
        hi = ord(f.read(1))
        startaddr = lo + 256*hi
        if startaddr < 512:
                print "ridiculous start address=", startaddr
                exit(0)

content = f.read()
length = len(content)
f.close()

print "\nLoading address:",startaddr,"length:",length, \
        "Blocks to send:",int((length+BLOCKSIZE+BLOCKSIZE-1)/BLOCKSIZE),"\n"

if TESTING < 1:
        ser = serial.Serial('/dev/ttyU0', 2400, stopbits=1, parity='N')
else:
        ser = open("/dev/zero", "rb")

ser.write(" ")                   # activate the rs232 on the cbm's side?
running = 1
p = 0
charssent = 0
start = 0

while running:
        if TESTING < 1:
                cin = ord(ser.read(1))
        else:
                cin = p
                p += 1

        if start == 0:
                start = time.time()

        print "BLK %3d " % cin,

        addr = cin * BLOCKSIZE
        if addr >= length:
                s = "& ff ff"
                sb = "&" + chr(255) + chr(255)
                running = 0
        else:
                addrend = min(addr + BLOCKSIZE, length)
                blklen = addrend - addr
                lo = (startaddr+addr) & 255
                hi = int((startaddr+addr) / 256)
                s = "& %02x " % lo + "%02x " % hi + "%02x :" % blklen
                sb = "&" + chr(lo) + chr(hi) + chr(blklen)

                cksum = lo + hi + blklen
                for i in range(addr,addrend):
                        c = ord(content[i])
                        cksum += c
                        s = s + " %02x" % c
                        sb = sb + content[i]

                cksum = cksum & 255
                s = s + " : %02x" % cksum
                sb = sb + chr(cksum)

        charssent += len(sb)
        sec = time.time() - start
        if sec >= 1:
                bps = int((1000 * charssent) / sec) / 1000
                s = s + " : " + str(bps) + " b/s"

        if TESTING > 0:
                print s
        if TESTING < 1:
                ser.write(sb)
                print "\r",
                sys.stdout.flush()
        if TESTING == 1:
                time.sleep(len(sb)*0.0042)

sec = time.time() - start
bps = int((1000 * charssent) / sec) / 1000
print
print bps," b/s"

ser.close()

###
